<template>
  <div class="app-container query-wrapper">
    <el-select  v-model="queryParams.vesselName" filterable clearable placeholder="Vessel" style="width:180px"
      @change="selectVessel">
      <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" style="width:110px">
      <el-option :key="item.voyageNo" ::label="item.voyageNo?item.voyageNo:''" :value="item.voyageNo?item.voyageNo:''" v-for="item in voyages">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.status" filterable clearable placeholder="Status" style="width:120px">
      <el-option :key="index" :label="item" :value="index" v-for="(item, index) in fullStatus"> </el-option>
    </el-select>
    &nbsp; &nbsp; 
    <el-button type="primary" icon="search" @click="search">{{ $t("ship.button.search") }}</el-button>
    <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
    <span>&nbsp;&nbsp;&nbsp;&nbsp; </span>
    <!-- <el-button type="primary" :disabled="listData.length == 0" @click="handleSubmit">
          Save
        </el-button>  -->
    <el-button type="warning" plain icon="download" :disabled="listData.length == 0" @click="exportClickEvent">
      Print
    </el-button>
  </div>
  <el-table ref="tableRef" stripe  v-loading="loading" :data="listData" :cell-style ="{textAlign:'center'}" style="width: 100%" @sort-change="handleSortChange"
    show-overflow-tooltip :header-cell-style="{textAlign:'center'}"  >
    <el-table-column prop="bookingNo" label="No." width="150" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="blNo" label="B/L No." width="150" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="Status" label="Status" width="120">
      <template #default="scope">{{ fullStatus[scope.row.status] }}</template>
    </el-table-column>
    <el-table-column prop="vesselName" label="Vessel" width="150" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="voyageNo" label="Voyage" width="90" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="countryName" width="140">
      <template #header="scope">
        Consignee<br/>Country
      </template>
    </el-table-column>
    <el-table-column prop="pol" label="POL" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="pod" label="POD" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="payer" width="140">
      <template #header="scope">
        Freight<br />Payable<br />Party
      </template>
    </el-table-column>
    <el-table-column prop="shipper" label="Shipper" width="150" sortable="custom" :sort-orders="['descending', 'ascending']" />
    <el-table-column prop="brand" label="Brand" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="model" label="Model" width="140" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="cargoDesc" label="Cargo Description" width="140">
      <template #header="scope">
        Cargo <br />Description
      </template>
    </el-table-column>
    <el-table-column prop="cargoType" label="Cargo Type" width="120" sortable="custom" :sort-orders="['descending', 'ascending']" />
    <el-table-column prop="fuelType" label="Fuel Type" width="120" sortable="custom" :sort-orders="['descending', 'ascending']" />

    <el-table-column prop="rate" label="" width="140">
      <template #header="scope">
        Freight <br />Rate
      </template>
    </el-table-column>
    <el-table-column prop="total" label="" width="140">
      <template #header="scope">
        Total<br />Freight
      </template>
    </el-table-column>
    <el-table-column prop="lashingHookFront" width="100" align="center">
      <template #header="scope">
        Lashing <br />Hook<br />(FRONT)
      </template>
      <template #default="scope">
        {{lashHookStatus[scope.row.lashingHookFront] }}
      </template>
    </el-table-column>
    <el-table-column prop="lashingHookRear" width="100" align="center">
      <template #header="scope">
        Lashing <br /> Hook<br />(REAR)
      </template>
      <template #default="scope">
        {{lashHookStatus[scope.row.lashingHookRear] }}
      </template>
    </el-table-column>
    <el-table-column prop="spareLocation" width="180" align="center">
      <template #header="scope">
        Spare Parts Location <br /> （Inside Vehicle / On Deck） <br />
      </template>
    </el-table-column>
    <el-table-column prop="totalUnits" label="total units" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="quantity" label="QTY" width="100" >
      <template #default="{scope,row}">
        {{row.quantity? row.quantity : row.totalUnits}}
      </template>
    </el-table-column>
    <el-table-column prop="unitLength" label="L" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    <el-table-column prop="unitWidth" label="W" width="100" sortable="custom" :sort-orders="['descending', 'ascending']" />
    <el-table-column prop="unitHeight" label="H" width="100" align="center" />
    <el-table-column prop="weight1" label="L+" width="100" align="center" />
    <el-table-column prop="weight2" label="W+" width="100" align="center" />
    <el-table-column prop="unitCbm" label="CBM" width="100" align="center">
      <template #default="{scope,row}">
        {{(row.unitLength*row.unitWidth*row.unitHeight).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalVolume" label="TTL CBM" width="100" align="center" >
      <template #default="{scope,row}">
        {{row.quantity?(row.unitLength*row.unitWidth*row.unitHeight*row.quantity).toFixed(3) :(row.unitLength*row.unitWidth*row.unitHeight* row.totalUnits) .toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="Weight(kg)" width="100" align="center"  />
    <el-table-column prop="totalWeight" width="100" align="center" >
      <template #header="scope">
        Total <br /> Weight(kg) <br />
      </template>
      <template #default="{scope,row}">
        {{row.quantity? (row.quantity*row.totalWeight).toFixed(0) : (row.totalUnits*row.totalWeight).toFixed(0) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="LL" width="100" align="center" >
      <template #default="{scope,row}">
        {{(row.weight1+row.unitLength).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="WW" width="100" align="center" >
      <template #default="{scope,row}">
        {{(row.weight2+row.unitWidth).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="L X W" width="100" align="center">
      <template #default="{scope,row}">
        {{(row.weight2+row.unitWidth).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="RT43" width="100" align="center">
      <template #default="{scope,row}">
        {{((row.weight2+row.unitWidth)/7.3).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="AEU" width="100" align="center">
      <template #default="{scope,row}">
        {{((row.weight2+row.unitWidth)/7.4).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="TTL AEU" width="100" align="center">
      <template #default="{scope,row}">
        {{row.quantity? ((row.weight2+row.unitWidth)*row.quantity/7.3).toFixed(3): ((row.weight2+row.unitWidth)*row.totalUnits/7.3).toFixed(3) }}
      </template>
    </el-table-column>
    <el-table-column prop="totalWeight" label="TTL RT43" width="100" >
      <template #default="{scope,row}">
        {{row.quantity? ((row.weight2+row.unitWidth)*row.quantity/7.4).toFixed(3): ((row.weight2+row.unitWidth)*row.totalUnits/7.4).toFixed(3) }}
      </template>
    </el-table-column>
</el-table>
<!-- </div>
  </div> -->

<pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
  @pagination="pageQuery" style="float: right" />


<el-dialog destroy-on-close draggable :width="1000" :title="dialogTitle" v-model="dialogFormVisible">
  <el-form :model="formParam" :rules="rules" ref="custForm">
    <el-row>
      <el-col :span="8">
        <el-form-item label="Length(m)" label-width="120px" prop="unitLength" required>
          <el-input-number v-model="formParam.unitLength" :precsion="3" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="Width(m)" label-width="120px" prop="unitWidth" required>
          <el-input-number v-model="formParam.unitWidth" :precsion="3" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="Height(m)" label-width="120px" prop="unitHeight" required>
          <el-input-number v-model="formParam.unitHeight" :precsion="3" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8">
        <el-form-item label="unit cbm" label-width="120px">
          <template #default="scope">
            {{
            (
            formParam.unitLength *
            formParam.unitHeight *
            formParam.unitWidth
            ).toFixed(2)
            }}
          </template>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="unit weight (kg)" label-width="120px" prop="unitWeight" required>
          <el-input type="number" v-model="formParam.unitWeight" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="total units" label-width="120px" prop="totalUnits" required>
          <el-input-number v-model="formParam.totalUnits" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="total volume（cbm）" label-width="200px">
          <template #default="scope">
            {{
            (
            formParam.unitLength *
            formParam.unitHeight *
            formParam.unitWidth *
            formParam.totalUnits
            ).toFixed(2)
            }}
          </template>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="Total Weight (kg)" label-width="200px" prop="totalWeight" required>
          <template #default="scope">
            {{ ((formParam.totalUnits || 0) * (formParam.unitWeight || 0)).toFixed(2) }}
          </template>
          <!-- <el-input-number v-model="formParam.totalWeight" disabled /> -->
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="Spare Parts Qty （Pcs)" label-width="170px" prop="totalVolume">
          <el-input type="number" v-model="formParam.spareQty" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="Spart Parts Location（in cab / on deck）" label-width="230px" prop="spareLocation">
          <el-input v-model="formParam.spareLocation" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="Spare Parts volume(cbm)" label-width="200px" prop="spareVolume">
          <el-input type="number" v-model="formParam.spareVolume" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="Spare Parts Weight(kg)" label-width="200px" prop="spareLocation">
          <el-input-number v-model="formParam.spareWeight" />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="B/L NO. 提单号" label-width="120px" prop="totalVolume">
            <el-input type="number" v-model="formParam.spareVolume" disabled />
          </el-form-item>
        </el-col>
      </el-row> -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="Remarks" label-width="120px" prop="remark">
          <el-input v-model="formParam.remark"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogFormVisible = false">{{
        $t("ship.button.cancel")
        }}</el-button>

      <el-button type="primary" @click="submitForm">{{
        $t("ship.button.submit")
        }}</el-button>
    </span>
  </template>
</el-dialog>
</template>
<script lang="ts" setup name="simulation">
  // @ts-nocheck
  import { ref, onMounted, reactive } from "vue";
  import service from "@/utils/request";
  import { ElNotification, ElMessageBox,ElMessage } from "element-plus";
  import { useTableDrag } from '@/hooks/useHooks';
  import { downloadFile } from "@/utils/downloadFile";
  import moment from "moment";
  const loading = ref(true)
  let fullStatus = ["draft", "confirmed", "waiting list", "close"]
  const { tableRef, proxy } = useTableDrag();
  let vessels = reactive([] as any);
  const lashHookStatus = [ "No","Yes"];
  const unitWeight = ref(null)
  const totalWeight = ref(null)
  const unitWeightFilter = ref({ unitWeight: { text: 'kg', value: 1 }, totalWeight: { text: 'kg', value: 1 } });
  const unitWeightFilterOptions = reactive([{ text: 'kg', value: 1 }, { text: 'ton', value: 1000 }]);
  const handleUnitWeightChange = (item: any, prop: string) => {
    unitWeightFilter.value[prop] = item
  }
  const toggleUnitWeightMenu = (prop: string) => {
    proxy?.$refs?.[prop]?.toggleMenu()
  }

  const custForm = ref();
  const dialogTitle = ref("");
  const initForm = {
    id: null,
    bookingNo: null,
    vesselName: null,
    voyageId: null,
    voyageNo: null,
    carrierName: null,
    channel: null,
    terminal: null,
    payer: null,
    shipper: null,
    consignee: null,
    notifyParty: null,
    pol: null,
    pod: null,
    brand: null,
    model: null,
    cargoDesc: null,
    lashingHookFront: null,
    lashingHookRear: null,
    carType: null,
    fuelType: null,
    unitLength: null,
    unitWidth: null,
    unitHeight: null,
    unitCbm: null,
    unitWeight: null,
    totalUnits: null,
    totalWeight: null,
    totalVolume: null,
    spareQty: null,
    spareLocation: null,
    spareVolume: null,
    spareWeight: null,
    remark: null,
    blNo: null,
    bookings: [] as any,
  };

  const initForm1 = {
    id: null,
    vesselName: null,
    voyageNo: null,
    carrierName: null,
    vesselId: null,
    bookings: [] as any,
  };
  const formParam = reactive(Object.assign({}, initForm));
  const formParam1 = reactive(Object.assign({}, initForm1));

  const total = ref(0);

  const rules = ref({
    companyId: [{ required: true, message: "carrier can't be blank" }],
  });

  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    voyageNo: null,
    orderByColumn: undefined,
    isAsc: undefined,
  });

  let carriers = ref([] as any);
  let voyages = ref([] as any);
  let ports = ref([] as any);
  let recordData = ref([] as any);
  const listData = ref([]);
  const refreshTable = async () => {
    loading.value = true
    let result = await service.get("/shipping/stowagePlan/getTable", {
      params: queryParams,
    });
    listData.value = result.data; 
    total.value = result.total;
      loading.value = false;
  };
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
  }
  const dialogFormVisible = ref(false);
  const dialogFormVisible1 = ref(false);
  const editClickEvent = (row: any) => {
    dialogTitle.value = "Update Slanning";
    dialogFormVisible.value = true;
    Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
    isAdd = false;
  };

  let isAdd = false;

  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };

  const submitForm = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      if (!valid) {
        // @ts-ignore
        ElNotification.warning({
          title: "Prompt information",
          message: "verification not success！",
          position: "bottom-right",
        });
        return;
      }

      // 统一处理数据
      if (isAdd) {
        formObj.value.recordData.forEach((item): any => {
          item.bookingNo = vesselCode + item.pol + "24001";
          item.unitCbm = (item.unitLength * item.unitWidth * item.unitHeight).toFixed(3);
          item.totalVolume = (item.unitCbm * item.totalUnits).toFixed(3);
          item.blNo = companyCode + vesselCode + voyageNo + item.pol + "001";
          item.totalWeight = item.totalUnits * item.unitWeight;
        });
        formParam.bookings = formObj.value.recordData;
      } else {
        formParam.bookingNo = vesselCode + formParam.pol + "24001";
        formParam.unitCbm = (
          formParam.unitLength *
          formParam.unitWidth *
          formParam.unitHeight
        ).toFixed(2);
        formParam.totalVolume = (formParam.unitCbm * formParam.totalUnits).toFixed(3);
        formParam.blNo = companyCode + vesselCode + voyageNo + formParam.pol + "001";
        formParam.totalWeight = formParam.totalUnits * formParam.unitWeight;
      }

      await service[isAdd ? "post" : "put"]("shipping/booking", formParam);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "save successful!",
        position: "bottom-right",
      });
      dialogFormVisible.value = false;
      refreshTable();
    });
  };

  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

  const search = () => {
    if((queryParams.vesselName == null || queryParams.voyageNo == null) ){
      listData.value = []
      total.value = 0
      ElMessage.warning( "please choose vesselName and Voyage!");
      return
    }
    refreshTable();
  };


  const uploadFile = async (event) => {
    if (event.target == null || event.target.files[0] == null) {
      return;
    }
    const formData = new FormData();
    formData.append("file", event.target.files[0]);
    await service["post"]("shipping/booking/uploadFile", formData);
  };

  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };

  const exportClickEvent = () => {
    //downloadFile("/shipping/stowagePlan/exportSimulation", queryParams, `${listData.value[0].vesselName}_${listData.value[0].voyageNo}_STOWAGE SIMULATION LIST_${moment(new Date()).format('YYYYMMDDHHmm')}.xlsx`);
    downloadFile("/shipping/stowagePlan/exportSimulation", queryParams, `STOWAGE SIMULATION LIST_${moment(new Date()).format('YYYYMMDDHHmm')}.xlsx`);
  }
  const handleSubmit = async () => {
    if (listData.value.length <= 0) {
      ElNotification.warning({
        title: "Prompt information",
        message: "no data to submit！",
        position: "bottom-right",
      });
      return;
    }

    ElMessageBox.confirm(
      "Confirm to send the declare information to approve？",
      "Confirmation Information",
      {
        type: "warning",
      }
    ).then(async () => {
      let params = { bookings: listData.value };
      await service.post(`shipping/booking/submit`, params);
      ElNotification.success({
        title: "Prompt information",
        message: "submit the data success!",
        position: "bottom-right",
      });
      //await service.delete(`shipping/booking/${id}`);
    });
  };

  const removeClickEvent = (id) => {
    ElMessageBox.confirm("Confirm to delete the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
      await service.delete(`shipping/booking/${id}`);
      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right",
      });
    });
  };

  let formObj = ref({
    recordData: [
      {
        id: 1,
        channel: "",
        terminal: "",
        payer: "",
        shipper: "",
        consignee: "",
        notifyParty: "",
        pol: "",
        pod: "",
        brand: "",
        model: "",
        cargoDesc: "",
        unitLength: null,
        unitWidth: null,
        unitHeight: null,
        unitCbm: null,
        unitWeight: null,
        totalUnits: null,
        totalVolume: null,
        totalWeight: null,
        spareQty: null,
        spareLocation: null,
        spareVolume: null,
        spareWeight: null,
        blNo: "",
      } as any,
    ],
  });

  let companyCode = "";
  let vesselCode = "";
  let voyageNo = "";
  const selectComapny = () => {
    let item = carriers.value.find((n) => n.carrierName == formParam.carrierName);
    if (item) {
      companyCode = item.companyCode;
    }
  };

  const selectVoyage = () => {
    let item = voyages.value.find((n) => n.voyagelId == formParam.voyageId);
    if (item) {
      voyageNo = item.voyageNo;
    }
  };

  onMounted(async () => {
    let result = await service.get("/shipping/schedule/getAllSchedule");
    if (result) {
      vessels = result.data;
    }

    let params = { status: 0 };

    result = await service.get("/shipping/voyage/list", { params: params });
    if (result) {
      voyages.value = result.data;
    }
    refreshTable();
  });

  const selectVessel = async () => {
    queryParams.voyageNo = null;
    //@ts-ignore
    let item = vessels.find(n => n.vesselName == queryParams.vesselName)
    voyages.value = item.schedules
  }
</script>